package com.miyake.loveviewweb.client.plugin;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.Key;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.miyake.loveviewweb.client.service.DataService;
import com.miyake.loveviewweb.shared.model.PluginModel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;

public class InstalledPluginList extends Composite {

    VerticalPanel panel = new VerticalPanel();
    Button buttonUninstall = new Button("Uninstall");

    public InstalledPluginList() {
        initWidget(panel);
        initialize();
    }

    private IPluginList pluginList;
    
    private void initialize() {
        panel.clear();
        panel.setWidth("100%");
        pluginList = new PluginListDataGrid();
        panel.add(pluginList.getWidgetUi());
        panel.add(buttonUninstall);
        
        //String[] services = {"FileParser", "DataProcessor"};
        
        DataService.Util.getInstance().getInstalledPlugins("*", new AsyncCallback<List<PluginModel>>() {
            public void onFailure(Throwable caught) {  
                Window.alert(caught.getMessage());
            }

            public void onSuccess(List<PluginModel> result) {
                pluginList.addData(PluginModelEx.getPluginModelEx(result));
            }
        });            
        
        buttonUninstall.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                List<Key> keys = new ArrayList<Key>();
                for (PluginModelEx m : pluginList.getData()) {
                    if (m.isSelected()) {
                        keys.add(m.getPluginModel().getKey());
                    }
                }
                
                DataService.Util.getInstance().uninstallPlugins(keys, new AsyncCallback<Void>() {

                    public void onFailure(Throwable caught) {
                        // TODO Auto-generated method stub
                        
                    }

                    public void onSuccess(Void result) {
                        initialize();
                    }
                    
                });
            }
            
        });
    }


    public void update() {
        initialize();
    }
}
